//
//  GuideViewController.swift
//  TimeBoat
//
//  Created by Jun on 2022/9/5.
//  Copyright © 2022 Time Boat. All rights reserved.
//

import Foundation


@objc class GuideViewController: BaseViewController {
    private var mTimer: Timer?
    private var mCount: Int = 3
    
    @IBOutlet var mSkipButton: UIButton!
    @IBOutlet var mLaucnImageView: UIImageView!
    
    @objc static func viewController() -> GuideViewController {
        let vc = GuideViewController()
        
        return vc
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.hideNaviBar = true
        loadADLaunchListData()
        createTimer()
        updateSkipButtonText()
    }
    
    deinit {
        Log.debug("==== deinit ====")
    }
    
    @discardableResult
    private func getADLaunchListData(completion: APICompletion<ADLauncheListItem>? = nil) -> APITASK? {
        let token = AccountManager.shareAccount().token()
        let frame = UIApplication.shared.keyWindow!.frame
        let width = frame.width
        let height = frame.height
        var params = [String: Any]()
        params["token"] = token
        params["width"] = width
        params["height"] = height
        return APIManager.shared.POST("ad/launch-list", params, completion)
    }
    
    public func loadADLaunchListData() {
        getADLaunchListData { result in
            if (result.suc) {
                if let list = result.dataList {
                    let item = list[0]
                    self.mLaucnImageView.sd_setImage(with: URL(string: item.adUrl!))
                }
            }
        }
    }
    
    private func createTimer() {
        if (nil == mTimer) {
            mTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerHandle), userInfo: nil, repeats: true);
            RunLoop.main.add(mTimer!, forMode: RunLoop.Mode.common)
            
            mCount = 3
        }
    }
    
    private func invalidateTimer() {
        mTimer?.invalidate()
        mTimer = nil
    }
    
    @objc func updateSkipButtonText() {
        let text = "跳过 \(mCount)"
        mSkipButton.setTitle(text, for: UIControl.State.normal)
    }
    
    @objc private func timerHandle() {
        mCount -= 1;
        updateSkipButtonText()
        
        if (mCount <= 0) {
            entryMain()
        }
    }
    
    @IBAction func btnSkipClick() {
        entryMain()
    }
    
    private func entryMain() {
        AppDelegateBridging.shared().configTab()
        
        invalidateTimer()
    }
}
